package providerConsume;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;


public class Provider implements Runnable{
	
	private BlockingQueue<Data> queue;
	
	//线程之间可以共享变量，同步可见
	private volatile boolean isRunning = true;
	
	private AtomicInteger count = new AtomicInteger();
	
	public Provider(BlockingQueue<Data> queue) {
		this.queue = queue;
	}
	
	@Override
	public void run() {
		while (isRunning) {
			int i = count.incrementAndGet();
			Data data = new Data(i, "数据_"+i);
			try {
				Thread.sleep(2000);
				
				System.out.println("当前线程:"+Thread.currentThread().getName()+",获取数据："+i+",添加到队列中...");
				if (!queue.offer(data, 2, TimeUnit.SECONDS)) {
					System.out.println("添加元素失败...");
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	public void stop(){
		this.isRunning = false;
	}

}
